package com.crcode.crm.service.meetingRecord.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.crcode.crm.bean.meetingRecord.MeetingRecordBean;
import com.crcode.crm.dao.meetingRecord.MeetingRecordDao;
import com.crcode.crm.service.meetingRecord.MeetingRecordService;
import com.crcode.crm.utils.DateUtil;
import com.crcode.crm.utils.MyFileUtil;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.ResultPageUtil;
import com.crcode.crm.utils.ResultUtil;
/**
 * 会议记录业务逻辑实现层
 * @author cl
 * @date 2019年3月25日
 */
@Service(value="meetingRecordService")
@Transactional
public class MeetingRecordServiceImpl implements MeetingRecordService {

	@Autowired
	private MeetingRecordDao meetingRecordDao;

	/**
	 * 根据序列化id查询
	 * @author: cl   
	 * @date: 2019年3月25日
	 * @param serializable
	 * @return
	 */
	@Override
	public MeetingRecordBean getById(Integer serializable) {
		return meetingRecordDao.findById(serializable).orElse(null);
	}

	/**
	 * 保存会议记录返回实体
	 * @author: cl   
	 * @date: 2019年3月25日  
	 * @param t
	 * @return
	 */
	@Override
	public MeetingRecordBean saveResultBean(MeetingRecordBean t) {
		return meetingRecordDao.save(t);
	}

	/**
	 * 保存会议记录返回true或false
	 * @author: cl   
	 * @date: 2019年3月25日 
	 * @param t
	 * @return
	 */
	@Override
	public boolean saveResultBoolean(MeetingRecordBean t) {
		try {
			meetingRecordDao.save(t);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public MeetingRecordBean updateResultBean(MeetingRecordBean t) {
		return null;
	}

	/**
	 * 查询所有
	 * @author: cl   
	 * @date: 2019年3月25日 
	 * @return
	 */
	@Override
	public boolean updateResultBoolean(MeetingRecordBean t) {
		return false;
	}

	/**
	 * 根据序号删除
	 * @author: cl   
	 * @date: 2019年3月25日 
	 * @param serializable
	 * @return
	 */
	@Override
	public boolean delete(Integer serializable) {
		try {
			meetingRecordDao.deleteById(serializable);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public List<MeetingRecordBean> getAll() {
		return meetingRecordDao.findAll();
	}

	/**
	 * 分页条件查询
	 * @author: cl   
	 * @date: 2019年3月25日
	 * @param params
	 * @param vo
	 * @return
	 */
	@Override
	public ResultPageUtil findAll(Map<String, Object> params, PageVo vo) {
		ResultPageUtil rp = new ResultPageUtil();
		Integer pageIndex = vo.getPageIndex() - 1;
		Pageable pageable =null;
		if(StringUtils.isNotEmpty(vo.getOrderBy())){
			if(vo.getOrderDesc()==1){
				pageable =PageRequest.of(pageIndex, vo.getPageSize(),Direction.DESC, vo.getOrderBy());
			}else if(vo.getOrderDesc()==0){
				pageable =PageRequest.of(pageIndex, vo.getPageSize(),Direction.ASC, vo.getOrderBy());
			}	
		}else{
			pageable =PageRequest.of(pageIndex, vo.getPageSize());
		}
		Page<MeetingRecordBean> page = meetingRecordDao.findAll(spec(params), pageable);
		rp.setPageSize(vo.getPageSize());
		rp.setCurrentPage(vo.getPageIndex());
		rp.setRows(page.getContent());
		rp.setTotal(page.getTotalElements());
		rp.setTotalPages(page.getTotalPages());
		return rp;
	}
	
	/**
	 * 创建动态查询条件组合
	 * @param params
	 * @return
	 */
    private Specification<MeetingRecordBean> spec(final Map<String,Object> params) {
    	Specification<MeetingRecordBean> spec = new Specification<MeetingRecordBean>() {
    		private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<MeetingRecordBean> root, CriteriaQuery<?> criteriaQuery,
					CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				
				//是否公开 0、非公开；1、公开
				if (params.get("isStats")!=null && params.get("isStats")!="") {
					predicates.add(cb.equal(root.get("isStats"), params.get("isStats")));
				}
				//会议时间检索
				if (params.get("startTime")!=null && params.get("startTime")!="") {
					predicates.add(cb.greaterThanOrEqualTo(root.get("meetTime").as(Date.class),DateUtil.StrToDate(params.get("startTime").toString()+" 00:00:00", "yyyy-MM-dd HH:mm:ss")));
				}
				if (params.get("endtTime")!=null && params.get("endtTime")!="") {
					predicates.add(cb.lessThanOrEqualTo(root.get("meetTime").as(Date.class),DateUtil.StrToDate(params.get("endtTime").toString()+" 23:59:59", "yyyy-MM-dd HH:mm:ss")));
				}
				//根据用户UUID查询是否可以看到
				if (params.get("user_uuid")!=null && params.get("user_uuid")!="" && !params.get("user_uuid").equals("admin")&& params.get("isPower").equals(true)) {
					predicates.add(cb.or(cb.equal(root.get("createUserUuid"),params.get("user_uuid")),
							cb.like(root.get("powerUserUuids"), "%"+params.get("user_uuid")+"%") ));
				}
				//检索关键字,匹配会议标题和会议简述
				if (params.get("searchWords")!=null && params.get("searchWords")!="") {
					predicates.add(cb.or(cb.like(root.get("meetTitle"), "%"+params.get("searchWords")+"%"),
							cb.like(root.get("meetContent"), "%"+params.get("searchWords")+"%") ));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		};
        return spec;
    }

    /**
     * 根据主键批量物理删除
     * @author: cl   
     * @date: 2019年3月25日 
     * @param ids
     * @return
     */
	@SuppressWarnings("rawtypes")
	@Override
	public ResultUtil physicalDeleteByIds(String ids) {
		ResultUtil r = new ResultUtil();
		String [] arr = ids.split(",");
		List<Integer> list=new ArrayList<>();
		for (String str : arr) {
			Integer id=Integer.parseInt(str);
			MeetingRecordBean m=meetingRecordDao.findById(id).orElse(null);
			if(m!=null){
				//删除文件
				if(StringUtils.isNotBlank(m.getMeetFilePath())){
					List<Map> files  = JSON.parseArray(m.getMeetFilePath(),Map.class);
					for(Map map:files){
						if(StringUtils.isNotBlank(map.get("filePath")+"")){
							MyFileUtil.deleteFile(map.get("filePath")+"");
						}
					}
				}
				list.add(Integer.parseInt(str));
			}
		}
		long count=meetingRecordDao.deleteByIdIn(list);
		Boolean flag=true;
		if(count==0){
			flag=false;
		}
		r.setObj(null);
		r.setInfo(flag?"删除成功！":"删除失败！");
		r.setStatus(flag);
		return r;
	}

	/**
	 * 根据名称和会议记录者UUID查询会议记录
	 * @param meetTitle
	 * @param createUserUuid
	 * @return
	 */
	public MeetingRecordBean findByMeetTitleAndCreateUserUuid(String meetTitle,String createUserUuid){
		return meetingRecordDao.findByMeetTitleAndCreateUserUuid(meetTitle,createUserUuid);
	}

	/**
	 * 根据主键批量审核
	 * @author: cl   
	 * @date: 2019年4月4日 
	 * @param ids
	 * @return
	 */
	@Override
	public ResultUtil batchAuditByIds(String ids,Integer isStatus) {
		ResultUtil r = new ResultUtil();
		String [] arr = ids.split(",");
		List<MeetingRecordBean> list=new ArrayList<>();
		String now=DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
		for (String str : arr) {
			MeetingRecordBean record = meetingRecordDao.getOne(Integer.parseInt(str));
			record.setIsStats(isStatus);
			record.setAuditTime(now);
			list.add(record);
		}
		List<MeetingRecordBean> saves=meetingRecordDao.saveAll(list);
		Boolean flag=true;
		if(saves.size()==0){
			flag=false;
		}
		r.setObj(null);
		r.setInfo(flag?"审核成功！":"审核失败！");
		r.setStatus(flag);
		return r;
	}

}
